package com.lambo.maven.core.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HttpUtil
 *
 * @author : lambo
 * @version : 1.0
 * @date :  2019-01-28 17:05
 **/
public class HttpUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static byte[] doGet(String httpUrl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        try {
            // 创建远程url连接对象
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                return IOUtil.readToByteBufferByLength(is, connection.getHeaderFieldInt("Content-Length", 0));
            }
            logger.info("doGet failed, responseCode = {}, url = {}", connection.getResponseCode(), httpUrl);
        } catch (IOException e) {
            logger.error("doGet failed, url = {}", httpUrl);
        } finally {
            // 关闭资源
            IOUtil.closeIo(is);
            if (null != connection) {
                connection.disconnect();// 关闭远程连接
            }
        }
        return null;
    }
}
